
package com.example.cia.mysql.dao.impl;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import com.example.cia.mysql.dao.ISightsDAO;

public class SightsDAO extends mysqlDaoImpl implements ISightsDAO{

	@Override
	public int addSights(String description) {
		String sql = "INSERT INTO "+getQulifiedTableName()+"("+getQueryFieldString(0)+")"+" VALUES(?)";
		Connection con;
		try {
			con = new databaseConnectionImpl().getCon();
			
			PreparedStatement ps = con.prepareStatement(sql,Statement.RETURN_GENERATED_KEYS);
			ps.setString(1, description);
			if(ps.executeUpdate()!=0){
				//如果执行成功
				ResultSet rs = ps.getGeneratedKeys();
				rs.next();
				int key = rs.getInt(1);
				rs.close();ps.close();con.close();
				return key;
			}
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return 0;
	}

	@Override
	public String getDescription(int id) {
		String sql = "SELECT "+getQueryFieldString(0)+" FROM "
	           +getQulifiedTableName()+" WHERE "+getPrimaryKey()+" = ?";
		try {
			Connection con = new databaseConnectionImpl().getCon();
			PreparedStatement ps = con.prepareStatement(sql);
			ps.setInt(1, id);
			ResultSet rs = ps.executeQuery();
			if(rs.next()){
				String description = rs.getString(1);
				return description;
			}else{
				return null;
			}
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	//修改获取表名
	@Override
	public String getTableName(){
		return "sights";
	}
	
	//修改查询字段
	@Override
	public String getQueryFieldString(int which){
		return getTableName()+"_description";
	}

}
